package org.hive.testserver.domain.model.schedule;

import org.hive.testserver.domain.model.Project;
import org.hive.testserver.domain.model.Slave;
import org.hive.testserver.domain.model.Test;
import org.hive.testserver.domain.model.TestRun;
import org.hive.testserver.domain.model.TestState;
import org.hive.testserver.domain.model.WorkSheet;

/**
 * Accept tests that are being executed the first time ever for a project.
 */
public class NewTestAllocator extends BaseAllocatorLink {

	public NewTestAllocator(AllocatorLink next) {
		super(next);
	}

	private static final long serialVersionUID = 1L;

	@Override
	protected ScheduleReason scheduledReason() {
		return ScheduleReason.NEW_TEST;
	}

	@Override
	protected boolean shouldAccept(Test test, Slave slave, WorkSheet workSheet) {
		return test.timesExecuted() == 0 && test.currentState() == TestState.UNTESTED && firstTestRunWithTest(test);
	}

	private boolean firstTestRunWithTest(Test test) {
		Project project = test.getTestRun().getProject();
		for (TestRun testRun : project.getTestRuns()) {
			if (testRun != test.getTestRun() && testRun.lookupTestByNameOrNull(test.getName()) != null) {
				return false;
			}
		}
		return true;
	}

}
